package com.ejuornal.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.ejuornal.bean.Message;
import com.ejuornal.bean.Page;
import com.ejuornal.dao.MessageDao;

@Component("messageDao")
public class MessageDaoImpl extends DaoSupport<Message> implements MessageDao {

	public void add(String sql, Object... objs) {
		super.add(sql, objs);
	}

	public void batchDelete(String sql, int... messageId) {
		super.batchDelete(sql, messageId);
	}

	public Message findById(long messageId) {
		String sql = "select *  from t_message where messageId = ?";

		Message message = super.getJdbcTemplate().queryForObject(sql,
				new Object[] { messageId }, new RowMapper<Message>() {

					public Message mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Message message = new Message();
						message.setContent(rs.getString("content"));
						message.setMessageId(rs.getLong("messageId"));
						message.setMessageType(rs.getString("messageType"));
						message.setReceiver(rs.getString("receiver"));
						message.setSender(rs.getString("sender"));
						message.setSentDate(rs.getDate("sendDate"));
						// message.setSentDate(rs.getDate("sender",
						// Calendar.getInstance()));
						message.setTitle(rs.getString("title"));

						return message;
					}
				});

		return message;
	}

	public Page<Message> findByProperty(String prpo, Object value) {
		return null;
	}

    @Override
    public Page<Message> find(int current_record, String url, String hsql, Object[] objs) {
        return super.find(current_record, url, hsql, objs);
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean findNew(String user_email) {
        String sql = "SELECT COUNT(*) FROM t_message where receiver=? and messageType=0";
        int num = super.getJdbcTemplate().queryForInt(sql, new Object[]{user_email});
        if(num > 0) {
            return true;
        }
        return false;
    }

	@Override
	public boolean delete(Long id) {
		String sql = "delete from t_message where messageId=?";
		int num = getJdbcTemplate().update(sql, new Object[] {id});
		if(num > 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean updateIsRead(int msgId) {
		String sql = "update t_message set messageType=1 where messageId=?";
		int num = getJdbcTemplate().update(sql, new Object[]{msgId});
		if(num >0) {
			return true;
		}
		return false;
	}
}
